package cn.com.dycc.notice.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.notice.dao.MessageDao;
import cn.com.dycc.notice.entity.Message;
import cn.com.dycc.notice.entity.MessageParam;
import cn.com.dycc.push.BaiduPush;
import cn.com.dycc.push.PushInfo;
import cn.com.dycc.sys_manage.deptsysmanagement.service.DeptNotFoundException;
import cn.com.dycc.sys_manage.usersysmanagement.dao.UserDao;
import cn.com.dycc.sys_manage.usersysmanagement.entity.User;
import cn.com.dycc.sys_manage.usersysmanagement.service.UserNotFoundException;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.Paging;
import cn.com.dycc.util.PropertiesUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 
 * Description: 通知公告业务层实现
 * Author: Liket
 * Version: 1.0
 * Create Date Time: 2017年10月19日 下午8:29:11.
 * Update Date Time: 
 * @see
 */

@Service("messageService")
public class MessageServiceImpl implements MessageService{
	@Resource
	private MessageDao messageDao;
	@Resource
	private UserDao userDao;
	@Resource
	private AttachDao attachDao;
	
	@Resource(name="paging")
	private Paging paging;
	
	
	/**
	 * 添加系统公告
	 * @throws IOException 
	 * @throws PushServerException 
	 * @throws PushClientException 
	 */	
	public int addMessage(MessageParam message,HttpServletRequest req) 
			throws UserNotFoundException,MessageNotFoundException, PushClientException, PushServerException, IOException {
		//检查参数格式
		if(message==null){
			throw new MessageNotFoundException("填写内容");
		}
		if(message.getContent()==null||message.getContent().trim().isEmpty()){
			throw new MessageNotFoundException("内容为空");
		}
		if(message.getTitle()==null||message.getTitle().trim().isEmpty()){
			throw new MessageNotFoundException("标题为空");
		}
		if(message.getVis()==null){
			message.setVis(0);
		}
		String content = message.getContent();
		content = content.replaceAll("&lte","<").replaceAll("&bte",">");
		message.setContent(content);
		HttpSession session = req.getSession();
		String id = (String) session.getAttribute("id");
		String account = (String) session.getAttribute("account");
		String username = (String) session.getAttribute("username");
		String ip = (String) session.getAttribute("userip");
		String org_id = (String) session.getAttribute("org_id");
		//String dept_no = (String) session.getAttribute("dept_no");
				
		//检查用户账号是否存在
		User user = userDao.findUserByAccount(account);
		if(user==null){
			throw new UserNotFoundException("用户名异常，请重新登录！");
		}	
		message.setUser_id(id);
		message.setAccount(account);
		message.setUsername(username);
		message.setSend_ip(ip);
		Timestamp timeDate = DateUtil.getNowTimestamp();
	//	System.out.println("addDate="+timeDate);
		message.setSend_date(timeDate);		
		message.setMessage_type(1);
		message.setOrg_id(org_id);		
		
		message.setAuto_send_date(timeDate);		
		message.setPush_message(1);
		message.setUpdate_date(timeDate);
		message.setUpdate_user_id(id);
		
		int n = messageDao.addMessage1(message);
		
		if(n!=1){
			throw new UserNotFoundException("添加公告失败！");
		}
		
		
		String message_id = message.getMessage_id();
		//System.out.println("id="+message_id);
		//System.out.println("m="+message);
		List<Attach> listAttach = new ArrayList<Attach>();
//		List<Attach> list=null;
//		try{
//			Gson gson=new Gson();
//			Attach[] array = gson.fromJson(materialparam.getListAttach(), Attach[].class);
//	       list= Arrays.asList(array);
//		}catch(Exception e){
//			System.out.println(e);
//		}
		
		if(message.getListAttach()!=null&&!message.getListAttach().trim().isEmpty()){
			String str=message.getListAttach().trim();
			//System.out.println(str);
			JSONArray json=JSONArray.fromObject(str);
			//System.out.println("l="+listAttach.size());
        
			for(int i=0;i<json.size();i++){

				//System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(message_id);
				attach.setAttach_type(60);
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(org_id);
				attach.setOpt_user_id(id);
				listAttach.add(attach);
								
			}        
        }
        //System.out.println(listAttach);
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"pro_material");
			
		//System.out.println("ATTACH"+newListAttach);
		if(newListAttach!=null){
		for(Attach attach:newListAttach){
			int a = attachDao.insertAttach(attach);
			//System.out.println(a);
				
			}
		}
		
		
		//发送公告成功后推送
        //手机标识
        Integer deviceType = 3;
//      Integer deviceType = (Integer)request.getSession().getAttribute("deviceType");
        
//      System.out.println("o="+apiKey+secretKey);
        //获取channelids
        
        //获取发布人头像
        //String icon_url = req.getSession().getAttribute("icon_url").toString();
        //获取发布人姓名
        //String send_username = userDao.findUserNameByUserId(id);
        
        //用于手机app前端数据展示
        JSONObject jsonObject = new JSONObject();        
        jsonObject.put("message_id", message_id);
        jsonObject.put("title", message.getTitle());
        jsonObject.put("content", content);
        jsonObject.put("send_date", DateUtil.getNowDate("yyyy-MM-dd"));
        //System.out.println("s="+message.getSend_date().toString());
        //System.out.println("d="+message.getSend_date());
        
        //JSONObject json = JSONObject.fromObject(message);
        //System.out.println("json"+json);
        
        //消息提示
        String messages = "";
        String title = "你有一条新的公告消息！";
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("topic","notice");
        map.put("data",jsonObject.toString());
        map.put("message","");
        map.put("state","");
        map.put("userId", "0");
        JSONObject notification = PushInfo.PushFormat(deviceType, messages, title, map);
//      System.out.println("lksa="+jsonArray.toString());
//      channelIds = jsonArray;
//      System.out.println("k="+channelIds);
//      System.out.println("gg="+Arrays.toString(channelIds));
        
//      String[] ci = {"4602637059594682449","4019688486852140065"};
//      System.out.println("c="+ci);
//      System.out.println("gg1="+Arrays.toString(ci));
//        String[] channelIds = (String[])aList.toArray(new String[aList.size()]);
//        System.out.println("gg1="+Arrays.toString(channelIds));
//        BaiduPush.pushBatchUniMsg(channelIds,notification,deviceType);
        BaiduPush.pushMsgToAll(notification, deviceType);
//      System.out.println("a="+Arrays.toString(i));
        //System.out.println("n="+notification.toString());
		
		return n;
		
	}
	
	/**
	 * 阅读公告
	 */
//	public MessageReceivePerson readMessage(Integer user_id, Integer message_id,String replay)
//			throws UserNotFoundException, MessageNotFoundException {
//		//参数检验
//		if(user_id==null){
//			throw new UserNotFoundException("请登录才能阅读公告");
//		}
//		if(message_id==null){
//			throw new MessageNotFoundException("请登录才能阅读公告");
//		}
//		//参数设置
//		MessageReceivePerson mrp = new MessageReceivePerson();
//		mrp.setUser_id(user_id);
//		mrp.setMessage_id(message_id);
//		mrp.setLook_date(new Date());
//		mrp.setState("已读");
//		mrp.setReplay(replay);
//		int n = mrPersonDao.updateMessageReceivePerson(mrp);
//		if(n!=1){
//			throw new MessageNotFoundException("系统繁忙");			
//		}
//		//修改阅读次数，参数设置
//		Message message = new Message();
//		message.setMessage_id(message_id);
//		int row = messageDao.updateMessage(message);
//		if(row!=1){
//			throw new MessageNotFoundException("系统繁忙，请稍后再试");
//		}		
//		return mrp;
//	}
	
	/**
	 * 显示公告
	 */
	public List<Message> listMessage(HttpServletRequest req,Integer page,Integer limit,String title) throws MessageNotFoundException {
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new MessageNotFoundException("显示公告列wxxcd[表失败");
		}
		List<Message> list = new ArrayList<Message>();
		
		//分页
		Integer start = null;
		
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}
		
		try {
			list = messageDao.listMessageByOrgId(org_id, title, start, limit);
		} catch (Exception e) {
			e.printStackTrace();
			throw new MessageNotFoundException("显示失败");
		}
		return list;
	}
	/**
	 * 删除公告
	 */
	public int deleteMessage(Message message) throws MessageNotFoundException {
		if(message.getMessage_id()==null){
			throw new MessageNotFoundException("公告ID为空");
		}
//		if(message.getTop_dept_no()==null){
//			throw new MessageNotFoundException("账号登录异常，请重新登录");
//		}
		//System.out.println(111111111);
		//int countMrpNo = mrPersonDao.countMessageReceivePerson(message.getMessage_id());
		//
		//System.out.println("countMrpNo"+countMrpNo);
		//int deleteMrpNo = mrPersonDao.deleteMessageReceivePerson(message.getMessage_id());
		//
		//System.out.println("deleteMrpNo"+deleteMrpNo);
//		if(countMrpNo!=deleteMrpNo){
//			throw new MessageNotFoundException("公告接收人删除失败");
//		}
//		int deleteMroNo = mrObjDao.deleteMessageReceiveObj(message.getMessage_id());
		//
		//System.out.println("deleteMroNo"+deleteMroNo);
//		if(deleteMroNo!=1){
//			throw new MessageNotFoundException("公告接收对象删除失败");
//		}
		int deleteM = messageDao.deleteMessage(message);
		//
		//System.out.println("deleteM"+deleteM);
		if(deleteM!=1){
			throw new MessageNotFoundException("公告删除失败");
		}
		return deleteM;
	}
	
	/**
	 * 更新公告
	 * @throws UnsupportedEncodingException 
	 */
//	public boolean updateMessage(Message message) throws MessageNotFoundException, UnsupportedEncodingException {
//		//获取传入的参数
//		Integer message_id = message.getMessage_id();
//		Integer message_type = message.getMessage_type();
//		String title = message.getTitle();
//		
//		//byte[] content = message.getContent();
//		Integer vis = message.getVis();
//		Date keep_date = message.getKeep_date();
//		Date send_date = message.getSend_date();
//		
//		if(message_id==null){
//			throw new MessageNotFoundException("公告ID找不到");
//		}
//		if(send_date==null){
//			throw new MessageNotFoundException("发布时间为空");
//		}
//		//根据公告ID获取实际的数据
//		Message lastMessage = messageDao.findMessageById(message.getMessage_id());
//		if(lastMessage==null){
//			throw new MessageNotFoundException("公告ID不存在");
//		}
//		
//		//设置新的数据
//		Message newMessage = new Message();
//		if(message_type!=null&&!message_type.equals(lastMessage.getMessage_type())){
//			newMessage.setMessage_type(message_type);
//		}
//		if(title!=null&&!title.equals(lastMessage.getTitle())){
//			newMessage.setTitle(title);
//		}
//		
//		if(message.getContent()!=null&&!message.getContent().equals(lastMessage.getContent())){
//			newMessage.setContent(message.getContent());
//		}
////		if(vis==0){
////			System.out.println("vis="+vis);
////		}
////		if(vis==null){
////			System.out.println("vis="+vis);
////		}
//		if(vis!=null&&vis!=lastMessage.getVis()){
//			newMessage.setVis(vis);
//		}
//		if(keep_date!=null&&!keep_date.equals(lastMessage.getKeep_date())){
//			newMessage.setKeep_date(keep_date);
//		}
//		if(send_date!=null&&!send_date.equals(lastMessage.getSend_date())){
//			newMessage.setSend_date(send_date);
//		}
//		newMessage.setMessage_id(message_id);		
//		int n = messageDao.updateMessage(newMessage);
//		if(n!=1){
//			throw new MessageNotFoundException("修改失败");
//		}
//		return n==1;
//	}

//	public int deleteMessageAll(Integer[] message_ids, HttpServletRequest req) throws MessageNotFoundException {
//		if(message_ids==null){
//			throw new MessageNotFoundException("请选择要删除的公告！");
//		}
//		HttpSession session = req.getSession();
//		Integer top_dept_no = (Integer) session.getAttribute("top_dept_no");
//		if(top_dept_no==null){
//			throw new MessageNotFoundException("登录信息异常！重新登录");
//		}
//		int mrpNum = mrPersonDao.countMRPAll(message_ids);
//		int delMrpNum = mrPersonDao.deleteMRPAll(message_ids);
//		if(mrpNum!=delMrpNum){
//			throw new MessageNotFoundException("删除公告接收人失败");
//		}
//		int mroNum = mrObjDao.countMessageReceiveObjAll(message_ids);
//		int delMroNum = mrObjDao.deleteMROAll(message_ids);
//		if(mroNum!=delMroNum){
//			throw new MessageNotFoundException("删除公告接受对象失败");
//		}
//		int delMessageNum = messageDao.deleteMessageAll(message_ids);
//		if(delMessageNum!=message_ids.length){
//			throw new MessageNotFoundException("删除公告失败");
//		}
//		return delMessageNum;
//	}

	public List<Message> listMessageByPage(Integer page,HttpServletRequest req) throws MessageNotFoundException, IOException{
		if(page==null){
			page=1;
		}
		HttpSession	session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null||org_id.trim().isEmpty()){
			throw new MessageNotFoundException("请重新登录");
		}
		String str = PropertiesUtil.readProperties("pageSize");
		
		int size =Integer.parseInt(str);
		int start = (page-1)*size;
		List<Message> list = messageDao.listMessageByPage(start, size);
		
		return list;		
	}

	public List<Message> findMessageById(String message_id,HttpServletRequest req) throws MessageNotFoundException {
		if(message_id==null){
			throw new MessageNotFoundException("id找不到");
		}
		HttpSession session = req.getSession();
		String org_id = (String)session.getAttribute("org_id");
		Message message = messageDao.findMessageById(message_id,org_id);
		if(message==null){
			throw new MessageNotFoundException("ID不存在");
		}
		List<Message> list = new ArrayList<Message>();
		list.add(message);
		return list;
	}

	public int countMessage(HttpServletRequest req) throws MessageNotFoundException {
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new MessageNotFoundException("登录异常");
		}
		int count = messageDao.countMessage(org_id);
		return count;
	}

	public List<Message> listMessageByParam(HttpServletRequest req,String send_date_start,String send_date_end,String title,String username) throws MessageNotFoundException, ParseException {
		
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		Message message = new Message();
//		message.setTitle(title);
//		message.setUsername(username);
//		if(send_date!=null){
//			//message.setSend_date(sdf.parse(send_date));
//		}
//		if(keep_date!=null){
//			//keep_date = sdf.parse(keep_date);
//			//message.setKeep_date(sdf.parse(keep_date));
//		}
//		if((keep_date==null)&&(title==null||title.trim().isEmpty())&&(username==null||username.trim().isEmpty())&&send_date==null){
//			throw new MessageNotFoundException("请输入条件查询!");
//		}
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("org_id", org_id);
		if(title!=null&&!title.trim().isEmpty()){
			param.put("title",title);
		}else{
			param.put("title","");
		}
		if(username!=null&&!username.trim().isEmpty()){
			param.put("username", username);
		}else{
			param.put("username", "");
		}
		if(send_date_start!=null&&!send_date_start.trim().isEmpty()){
			param.put("send_date_start", send_date_start);
		}
		
		if(send_date_end!=null&&!send_date_end.trim().isEmpty()){
			param.put("send_date_end", send_date_end);
		}
		//System.out.println("param="+param);
		List<Message> list = messageDao.listMessageByParam(param);
//		if(list.isEmpty()){
//			throw new MessageNotFoundException("查询无结果!");
//		}
		return list;
	}

	public int deleteMessageAll(String[] message_ids, HttpServletRequest req) throws MessageNotFoundException {
		if(message_ids==null){
			throw new MessageNotFoundException("找不到删除的公告");
		}
		if(message_ids.length<0||message_ids.length==0){
			throw new MessageNotFoundException("请选择要删除的公告");
		}
		String org_id = (String) req.getSession().getAttribute("org_id");
		if(org_id==null){
			throw new MessageNotFoundException("请重新登录");
		}
		List<String> list = Arrays.asList(message_ids);
		int n = messageDao.deleteMessageAll(list,org_id);
		
		return n;
	}

	public boolean updateMessage(MessageParam message, HttpServletRequest req)
			throws MessageNotFoundException, UnsupportedEncodingException {
		//System.out.println("message="+message);
		if(message==null){
			throw new MessageNotFoundException("修改信息为空");
		}
		if(message.getMessage_id()==null||message.getMessage_id().trim().isEmpty()){
			throw new MessageNotFoundException("找不到ID");
		}
		if(message.getTitle()==null||message.getTitle().trim().isEmpty()){
			throw new MessageNotFoundException("标题不能为空");
		}
		if(message.getContent()==null||message.getContent().trim().isEmpty()){
			throw new MessageNotFoundException("内容不能为空");
		}
		String content = message.getContent();
		content = content.replaceAll("&lte","<").replaceAll("&bte",">");
		//message.setContent(content);
		HttpSession session = req.getSession();
		//修改人id
		String update_user_id = (String) session.getAttribute("id");
		String org_id = (String) session.getAttribute("org_id");
		//获取实际值
		Message lastMessage = messageDao.findMessageById(message.getMessage_id(),org_id);
//		System.out.println("message_id="+message.getMessage_id());
		System.out.println("lastMessage="+lastMessage);
		if(lastMessage==null){
			throw new MessageNotFoundException("公告不存在");
		}
		Message updateMessage = new Message();
		if(!message.getTitle().equals(lastMessage.getTitle())){
			updateMessage.setTitle(message.getTitle());
		}
		if(!content.equals(lastMessage.getContent())){
			updateMessage.setContent(content);
		}
		if(message.getVis()!=null&&!(message.getVis().equals(lastMessage.getVis()))){
			updateMessage.setVis(message.getVis());
		}
		updateMessage.setMessage_id(message.getMessage_id());
		updateMessage.setOrg_id(org_id);
		updateMessage.setUpdate_user_id(update_user_id);
		updateMessage.setUpdate_date(DateUtil.getNowTimestamp());
		int count = messageDao.updateMessage(updateMessage);
		if(count!=1){
			throw new MessageNotFoundException("修改失败");
		}
		
		String message_id = message.getMessage_id();
		//System.out.println("id="+message_id);
		//System.out.println("m="+message);
		List<Attach> listAttach = new ArrayList<Attach>();
//		List<Attach> list=null;
//		try{
//			Gson gson=new Gson();
//			Attach[] array = gson.fromJson(materialparam.getListAttach(), Attach[].class);
//	       list= Arrays.asList(array);
//		}catch(Exception e){
//			System.out.println(e);
//		}
		
		if(message.getListAttach()!=null&&!message.getListAttach().trim().isEmpty()){
			String str=message.getListAttach().trim();
			//System.out.println(str);
			JSONArray json=JSONArray.fromObject(str);
			//System.out.println("l="+listAttach.size());
        
			for(int i=0;i<json.size();i++){

				//System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(message_id);
				attach.setAttach_type(60);
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(org_id);
				attach.setOpt_user_id(update_user_id);
				listAttach.add(attach);
				//System.out.println(attach_ext);
				////System.out.println(attach_path);
				//System.out.println(attach_size);
				//System.out.println(title);
				
				
			}
        
        }
        //System.out.println(listAttach);
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"pro_material");
			
			//System.out.println("ATTACH"+newListAttach);
			if(newListAttach!=null){
			for(Attach attach:newListAttach){
				int a = attachDao.insertAttach(attach);
				//System.out.println(a);
					
				}
			}
		return count==1;
	}
	
	//公告列表查询统计 20180510linfangan
	public String findMessAgeCount(HttpServletRequest req, String title) throws MessageNotFoundException {
		
		String org_id = req.getSession().getAttribute("org_id").toString();
		String count = null;
		try {
			count = messageDao.findMessAgeCount(org_id, title);
		} catch (Exception e) {
			e.printStackTrace();
			throw new MessageNotFoundException("查询失败！请稍后重试");
		}
		return count;
	}

	
		
	
}
